const fs = require('fs')
const path = require('path')
console.log('=================================================================================');

let rootPath = path.join(__dirname)
// console.log(rootPath);
// console.log(__dirname);
let rootPathReg = new RegExp(String(__dirname))
rootPathReg = rootPath.replace(rootPathReg, '')
let ignoreDir = /img|images/i
let obj = {}
let readmeStr = ''

function readDirSync(_path) {
    var pa = fs.readdirSync(_path);
    // console.log(pa);
    pa.forEach(function (dirOrFileName, index) {
        let info = fs.statSync(_path + "/" + dirOrFileName)

        if (info.isDirectory()) {
            if (!(/^\./.test(dirOrFileName) || ignoreDir.test(dirOrFileName))) {
                readDirSync(_path + "/" + dirOrFileName);
            }
        } else {
            if ((!/(^\.)/.test(dirOrFileName)) && /\.md$/.test(dirOrFileName)) {
                let mdFileName = dirOrFileName
                let p = _path.replace(rootPathReg, '')
                // console.log(p, mdFileName);
                if (p) {
                    let fileNameArr = p.split('/')
                    // console.log(fileNameArr);
                    // 给obj对象去重/新增对象，并生成该路径下md文档的软连接字符串temp
                    let temp = fileNameArr.reduce((pre, curr, currIdx) => {
                        if (curr) {
                            let res = ''
                            // console.log('pre,curr:', pre, curr);
                            // console.log(curr);
                            // 处理文件夹下既有md文件也有文件夹的情况 - 1（在md文件前面虚拟增加一个以该文件名命名的文件夹）
                            if (typeof eval(pre) === 'string' && curr) {
                                let a = eval(pre) + ""
                                let head = a.match(/\[([^ ]+)\]/)[1]
                                eval(pre + '={}')
                                eval(pre)[head] = a
                                console.log('head:', head, 'pre:', eval(pre));
                            }

                            res = pre + `['${curr}']`
                            // console.log('res:', res, eval(res));
                            // console.log('pre,curr:', pre, curr);
                            // console.log(currIdx, fileNameArr.length - 1);
                            if (currIdx === (fileNameArr.length - 1)) {
                                if (!eval(res)) eval(res + '=""')
                            } else {
                                if (!(eval(res))) eval(res + '={}')
                            }
                            return res
                        }
                        return pre
                    }, 'obj')

                    // 通过修改temp，从而修改obj
                    // console.log('temp:', temp, eval(temp));
                    let head = mdFileName.replace(/\.md$/, '')
                    if (typeof eval(temp) === 'string') {
                        eval(temp + "+=" + ("`- [${head}](.${p}/${mdFileName})`"))
                    } else {
                        // 处理文件夹下既有md文件也有文件夹的情况 - 2（在md文件前面虚拟增加一个以该文件名命名的文件夹）
                        eval(temp + "[head]=" + ("`- [${head}](.${p}/${mdFileName})`"))
                    }
                }
            }
        }
    })
}

readDirSync(rootPath)
// console.log('obj:', obj);
let keys = [], deep = 0
JSON.stringify(obj, (key, val) => {
    if (!key) return val
    let str = ''
    // console.log("deep:", deep);
    // console.log("key:", key);
    // console.log("val:", val);
    for (let index = 0; index < deep; index++) {
        str += '#'
    }

    readmeStr += (str + "## " + key + '\n')
    if (typeof val === 'object') {
        keys = [...Object.keys(val)]
        ++deep
        return val
    } else if (typeof val === 'string') {
        // console.log(keys, key);
        let idx = keys.findIndex(v => key === v)
        if (typeof idx === 'number') {
            keys.splice(idx, 1)
        }
        if ((keys.length === 0) && (deep > 0)) {
            deep = 0
        }
        readmeStr += (val.replace(/(- )/g, '\n - ') + '\n')
        return val
    }
}, 2)

fs.writeFile('./README.md',
    readmeStr,
    e => {
        console.log(e);
    })
console.log('=================================================================================');
